import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_ahj_app/base/basewidget/view/BaseWidget.dart';
import 'package:flutter_ahj_app/base/utils/mTopBar.dart';
import 'package:flutter_ahj_app/base/values/SQColor.dart';
import 'package:flutter_ahj_app/base/values/dimens.dart';

import 'ForgetPWDViewModel.dart';

class ForgetPWD1 extends BaseStatefulWidget {
  @override
  State<StatefulWidget> initState() {
    return ForgetPWDSate();
  }
}

class ForgetPWDSate extends BaseState<ForgetPWDViewModel, ForgetPWD1> {
  Widget _tfPhone;
  String _phone = "";
  Widget _tfCheck;
  String _check = "";
  Widget _checkView;
  Widget _nextStep;

  String _errorPhone;
  String _errorCheck;

  String _checkText = "获取验证码";
  Timer countDownTimer; //获取验证码计时器

  @override
  Widget initWidget() {
    initView();
    return Scaffold(
      appBar: MTopBar(title: "找回密码").create(),
      body: _bodView(),
    );
  }

  void initView() {
    _tfPhone = TextField(
      style: TextStyle(color: SQColor.per87Black, fontSize: Dimens.textSize32),
      controller: TextEditingController.fromValue(
        TextEditingValue(
            text: _phone,
            selection: TextSelection.fromPosition(TextPosition(
                affinity: TextAffinity.downstream, offset: _phone.length))),
      ),
      keyboardType: TextInputType.phone,
      decoration: InputDecoration(
        labelText: "手机号",
        errorText: _errorPhone,
      ),
      onChanged: (String str) {
        _phone = str;
        setState(() {
          _phone = str;
          RegExp exp = RegExp('^^(1[3-9])\\d{9}\$');
          bool matched = exp.hasMatch(_phone);
          if (_phone != null && _phone.length == 11 && matched) {
            _errorPhone = null;
          } else {
            _errorPhone = "请输入正确格式的手机号";
          }
        });
      },
    );
    _tfCheck = TextField(
      maxLength: 10,
      style: TextStyle(color: SQColor.per87Black, fontSize: Dimens.textSize32),
      controller: TextEditingController.fromValue(
        TextEditingValue(
            text: _check,
            selection: TextSelection.fromPosition(TextPosition(
                affinity: TextAffinity.downstream, offset: _check.length))),
      ),
      keyboardType: TextInputType.phone,
      decoration: InputDecoration(
        counterText: '',
        labelText: "验证码",
        errorText: _errorCheck,
      ),
      onChanged: (String str) {
        setState(() {
          _check = str;
          if (_check != null && _check.length > 0) {
            _errorCheck = null;
          } else {
            _errorCheck = "请输入验证码";
          }
        });
      },
    );
    _checkView = _tfCheck;
    _checkView = Stack(
      alignment: Alignment.centerRight,
      children: <Widget>[
        _tfCheck,
        GestureDetector(
          child: Text(
            _checkText,
            style: TextStyle(
                fontSize: Dimens.textSize28,
                color: _checkText == "获取验证码"
                    ? SQColor.theme_color
                    : SQColor.per38Black),
          ),
          onTap: _checkText == "获取验证码" ? () => _getCheckCode() : null,
        ),
      ],
    );
    _nextStep = MaterialButton(
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.circular(Dimens.dimens8))),
      color: SQColor.theme_color,
      textColor: SQColor.white,
      disabledColor: SQColor.black_b2b2b2,
      disabledTextColor: SQColor.black_8e8e8e,
      minWidth: double.infinity,
      height: Dimens.dimens48,
      onPressed: () => _next(),
      child: Text(
        "下一步",
        style: TextStyle(fontSize: Dimens.textSize28),
      ),
    );
  }

  _bodView() {
    return Padding(
      padding: EdgeInsets.fromLTRB(
          Dimens.dimens32, Dimens.dimens64, Dimens.dimens32, 0),
      child: Column(
        children: <Widget>[
          _tfPhone,
          Container(height: Dimens.dimens32),
          _checkView,
          Container(height: Dimens.dimens64),
          _nextStep,
        ],
      ),
    );
  }

  // 获取验证码
  _getCheckCode() {
    RegExp exp = RegExp('^^(1[3-9])\\d{9}\$');
    bool matched = exp.hasMatch(_phone);
    if (!matched) {
      setState(() {
        _errorPhone = "请输入正确格式的手机号";
      });
      return;
    }

    countDownTimer?.cancel(); //如果已存在先取消置空
    countDownTimer = null;
    setState(() {
      _checkText = "60秒";
    });
    countDownTimer = new Timer.periodic(new Duration(seconds: 1), (t) {
      setState(() {
        if (60 - t.tick > 0) {
          //60-t.tick代表剩余秒数，如果大于0，设置yzmText为剩余秒数，否则重置yzmText，关闭countTimer
          _checkText = "${60 - t.tick}秒";
        } else {
          _checkText = '获取验证码';
          countDownTimer.cancel();
          countDownTimer = null;
        }
      });
    });

    viewModel.getCode(_phone);
    viewModel.getCodeStream().listen((result) {
      if (result == null) {
        // 获取验证码失败
        setState(() {
          _checkText = '获取验证码';
          countDownTimer.cancel();
          countDownTimer = null;
        });
      } else if (result.code != 0) {
        // 获取验证码失败
        setState(() {
          _checkText = '获取验证码';
          countDownTimer.cancel();
          countDownTimer = null;
        });
      }
    });
  }

  // 下一步
  _next() {
    RegExp exp = RegExp('^^(1[3-9])\\d{9}\$');
    bool matched = exp.hasMatch(_phone);
    if (!matched) {
      setState(() {
        _errorPhone = "请输入正确格式的手机号";
      });
      return;
    }

    if (_check == null || _check.length == 0) {
      setState(() {
        _errorCheck = "请输入验证码";
      });
      return;
    }

    viewModel.checkCode(_phone, _check);
    viewModel.checkCodeStream().listen((result) {
      if (result == null) {
        // 验证验证码失败
      } else {
        // result.data 是接口返回的token
        if (result.code == 0) {
          var map = {
            'phone': _phone,
            'token': result.data,
          };
          Navigator.pushNamed(context, "/ForgetPWD2", arguments: map)
              .then((value) {
            if (value != null && value == "success") {
              Navigator.pop(context, "success");
            }
          });
        }
      }
    });
  }

  @override
  void dispose() {
    countDownTimer?.cancel();
    countDownTimer = null;
    super.dispose();
  }
}
